package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.DeliveryManagementDetailMapper;
import com.intelligent.mapper.DeliveryManagementMapper;
import com.intelligent.mapper.ProductMapper;
import com.intelligent.mapper.UnitMapper;
import com.intelligent.pojo.DeliveryManagement;
import com.intelligent.pojo.DeliveryManagementDetail;
import com.intelligent.pojo.Product;
import com.intelligent.pojo.Unit;
import com.intelligent.service.DeliveryManagementDetailService;
import com.intelligent.vo.DeliveryDetailPageReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeliveryManagementDetailServiceImpl extends ServiceImpl<DeliveryManagementDetailMapper, DeliveryManagementDetail>
    implements DeliveryManagementDetailService {

    @Autowired
    private DeliveryManagementMapper deliveryManagementMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Override
    public Page<DeliveryManagementDetail> page(DeliveryDetailPageReq req) {
        Page<DeliveryManagementDetail> page = new Page<>(req.getPageNum() == null ? 1 : req.getPageNum(),
                req.getPageSize() == null ? 10 : req.getPageSize());
        LambdaQueryWrapper<DeliveryManagementDetail> wrapper = new LambdaQueryWrapper<>();
        if (req.getDeliveryOrderId() != null) {
            wrapper.eq(DeliveryManagementDetail::getDeliveryOrderId, req.getDeliveryOrderId());
        }
        if (req.getProductId() != null) {
            wrapper.eq(DeliveryManagementDetail::getProductId, req.getProductId());
        }

        wrapper.orderByDesc(DeliveryManagementDetail::getId);
        Page<DeliveryManagementDetail> result = this.page(page, wrapper);

        // 填充发货单号、状态和产品信息
        fillDeliveryOrderNo(result.getRecords());
        fillStatusText(result.getRecords());
        fillProductInfo(result.getRecords());

        return result;
    }


    private void fillDeliveryOrderNo(List<DeliveryManagementDetail> details) {
        if (details == null || details.isEmpty()) {
            return;
        }

        // 获取所有发货单ID
        List<Long> deliveryOrderIds = details.stream()
                .map(DeliveryManagementDetail::getDeliveryOrderId)
                .distinct()
                .collect(Collectors.toList());

        if (deliveryOrderIds.isEmpty()) {
            return;
        }

        // 批量查询发货单信息
        LambdaQueryWrapper<DeliveryManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeliveryManagement::getId, deliveryOrderIds);
        List<DeliveryManagement> deliveries = deliveryManagementMapper.selectList(wrapper);

        // 构建ID到发货单号的映射
        Map<Long, String> idToOrderNoMap = deliveries.stream()
                .collect(Collectors.toMap(
                    DeliveryManagement::getId,
                    DeliveryManagement::getDeliveryOrderNo,
                    (existing, replacement) -> existing
                ));

        // 填充发货单号
        details.forEach(detail -> {
            String orderNo = idToOrderNoMap.get(detail.getDeliveryOrderId());
            if (orderNo != null) {
                detail.setDeliveryOrderNo(orderNo);
            }
        });
    }


    private void fillStatusText(List<DeliveryManagementDetail> details) {
        if (details == null || details.isEmpty()) {
            return;
        }

        // 获取所有发货单ID
        List<Long> deliveryOrderIds = details.stream()
                .map(DeliveryManagementDetail::getDeliveryOrderId)
                .distinct()
                .collect(Collectors.toList());

        if (deliveryOrderIds.isEmpty()) {
            return;
        }

        // 批量查询发货单信息
        LambdaQueryWrapper<DeliveryManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeliveryManagement::getId, deliveryOrderIds);
        List<DeliveryManagement> deliveries = deliveryManagementMapper.selectList(wrapper);

        // 构建ID到出库状态的映射
        Map<Long, Integer> idToOutboundStatusMap = deliveries.stream()
                .collect(Collectors.toMap(
                    DeliveryManagement::getId,
                    DeliveryManagement::getOutboundStatus,
                    (existing, replacement) -> existing
                ));

        // 填充状态文本
        details.forEach(detail -> {
            Integer outboundStatus = idToOutboundStatusMap.get(detail.getDeliveryOrderId());
            String statusText = convertOutboundStatusToText(outboundStatus);
            detail.setOutboundStatusText(statusText);
        });
    }


    private String convertOutboundStatusToText(Integer outboundStatus) {
        if (outboundStatus == null) {
            return "未知";
        }
        switch (outboundStatus) {
            case 0:
                return "全部出库";
            case 1:
                return "部分出库";
            case 2:
                return "未出库";
            default:
                return "未知";
        }
    }

    private void fillProductInfo(List<DeliveryManagementDetail> details) {
        if (details == null || details.isEmpty()) {
            return;
        }

        // 获取所有产品ID
        List<Long> productIds = details.stream()
                .map(DeliveryManagementDetail::getProductId)
                .distinct()
                .collect(Collectors.toList());

        if (productIds.isEmpty()) {
            return;
        }

        // 批量查询产品信息
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.in(Product::getProductId, productIds);
        List<Product> products = productMapper.selectList(productWrapper);

        // 构建产品ID到产品信息的映射
        Map<Long, Product> productMap = products.stream()
                .collect(Collectors.toMap(
                    Product::getProductId,
                    product -> product,
                    (existing, replacement) -> existing
                ));

        // 获取所有单位ID
        List<Long> unitIds = products.stream()
                .map(Product::getUnitId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询单位信息
        Map<Long, String> unitMap;
        if (!unitIds.isEmpty()) {
            LambdaQueryWrapper<Unit> unitWrapper = new LambdaQueryWrapper<>();
            unitWrapper.in(Unit::getUnitId, unitIds);
            List<Unit> units = unitMapper.selectList(unitWrapper);
            unitMap = units.stream()
                    .collect(Collectors.toMap(
                        Unit::getUnitId,
                        Unit::getUnitName,
                        (existing, replacement) -> existing
                    ));
        } else {
            unitMap = new HashMap<>();
        }

        // 填充产品信息
        details.forEach(detail -> {
            Product product = productMap.get(detail.getProductId());
            if (product != null) {
                detail.setProductName(product.getProductName());
                detail.setProductCode(product.getProductCode());
                detail.setSpecification(product.getSpecification());
                detail.setCategory(convertCategoryToText(product.getCategory()));

                // 填充单位名称
                String unitName = unitMap.get(product.getUnitId());
                if (unitName != null) {
                    detail.setUnitName(unitName);
                }
            }
        });
    }

    private String convertCategoryToText(Integer category) {
        if (category == null) {
            return "未知";
        }
        switch (category) {
            case 0:
                return "成品";
            case 1:
                return "半成品";
            case 2:
                return "残次品";
            default:
                return "未知";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeliveryManagementDetail create(DeliveryManagementDetail detail) {
        this.save(detail);
        return detail;
    }

    @Override
    public DeliveryManagementDetail detail(Long id) {
        return this.getById(id);
    }
}




